package com.moji.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.moji.common.entity.MyPage;
import com.moji.common.utils.DateUtils;
import com.moji.common.utils.HttpUtils;
import com.moji.common.utils.PageUtil;
import com.moji.entity.*;
import com.moji.entity.dto.AddOrderDto;
import com.moji.entity.dto.QueryOrderDto;
import com.moji.entity.vo.*;
import com.moji.mapper.MjOrderMapper;
import com.moji.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moji.util.IdGenerator;
import com.moji.util.MoJiCommonUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author ccl
 * @since 2024-07-27
 */
@Service
public class MjOrderServiceImpl extends ServiceImpl<MjOrderMapper, MjOrder> implements MjOrderService {

    @Resource
    private MjOrderDetailService mjOrderDetailService;

    @Resource
    private MjAgreementService mjAgreementService;

    @Resource
    private MjUserService mjUserService;

    @Resource
    private MjBillService mjBillService;

    @Resource
    private IdGenerator idGenerator;

    @Override
    public MyPage<MjOrder> queryByPage(QueryOrderDto dto) {
        LambdaQueryWrapper<MjOrder> wrapper = new LambdaQueryWrapper<>();
        //手机号
        wrapper.like(ObjectUtil.isNotEmpty(dto.getMobile()), MjOrder::getMobile
                , dto.getMobile());
        //订单号
        wrapper.like(ObjectUtil.isNotEmpty(dto.getOrderCode()), MjOrder::getOrderCode
                , dto.getOrderCode());
        //订单状态
        wrapper.eq(ObjectUtil.isNotEmpty(dto.getOrderStatus()), MjOrder::getOrderStatus
                , dto.getOrderStatus());
        //发票状态
        wrapper.eq(ObjectUtil.isNotEmpty(dto.getBillStatus()), MjOrder::getBillStatus
                , dto.getBillStatus());
        //发票分页
        if (ObjectUtil.isNotEmpty(dto.getQueryType()) && dto.getQueryType() == 1) {
            wrapper.ne(MjOrder::getProductType, "1");
        }
        wrapper.eq(MjOrder::getCreateId, MoJiCommonUtils.getUserCode());
        //创建时间倒叙
        wrapper.orderByDesc(MjOrder::getUpdateTime);
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<MjOrder> mjOrders = list(wrapper);
        if (ObjectUtil.isNotEmpty(mjOrders)) {
            mjOrders.forEach(mjOrder -> {
                if (mjOrder.getSpareInt1() != null) {
                    if (mjOrder.getSpareInt1() == 3) {
                        mjOrder.setRefuse(false);
                    } else {
                        mjOrder.setRefuse(true);
                    }
                } else {
                   if(mjOrder.getPayTime()==null)
                   {
                       mjOrder.setRefuse(false);
                   }else{
                       mjOrder.setRefuse(true);
                   }


                }

                MjBill mjBill = mjBillService.getOne(new LambdaQueryWrapper<MjBill>()
                        .eq(MjBill::getOrderCode, mjOrder.getOrderCode())
                        .eq(MjBill::getUserCode, mjOrder.getUserCode()));
                if (mjBill != null) {
                    mjOrder.setBillUrl(mjBill.getBillUrl());
                }
            });
        }
        PageInfo<MjOrder> info = new PageInfo<>(mjOrders);
        return PageUtil.PageInfo2MyPage(info);
    }

    @Override
    public boolean delete(Long id) {
        MjOrder mjOrder = this.getById(id);
        if (mjOrder == null) {
            throw new RuntimeException("主键ID不能为空,请核查!");
        }
        LambdaQueryWrapper<MjOrderDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MjOrderDetail::getOrderMxCode, mjOrder.getOrderCode());
        mjOrderDetailService.remove(wrapper);

        return this.removeById(id);
    }

    @Override
    public MjOrder add(AddOrderDto addOrderDto) {
        MjOrder mjOrder = new MjOrder();
        BeanUtils.copyProperties(addOrderDto, mjOrder);
        String orderCode = idGenerator.idGenerator("DD");
        mjOrder.setOrderCode(orderCode);
        mjOrder.setBillStatus(0);
        mjOrder.setOrderStatus(0);
        MjUser mjUser = mjUserService.getOne(new LambdaQueryWrapper<MjUser>()
                .eq(MjUser::getUserCode, MoJiCommonUtils.getUserCode()));
        mjOrder.setUserCode(mjUser.getUserCode());
        mjOrder.setUserName(mjUser.getUserName());
        mjOrder.setMobile(mjUser.getMobile());
        mjOrder.setAccountType(mjUser.getUserType() == 0 ? "个人账户" : "企业账户");
        mjOrder.setOriginalAmount(addOrderDto.getOrderAmount());
        mjOrder.setCompanyCode(mjUser.getCompanyCode());
        mjOrder.setOrderTime(new Date());
        mjOrder.setCompanyName(mjUser.getCompanyName());
        mjOrder.setUserName(MoJiCommonUtils.getUserName());
        mjOrder.setCreateId(MoJiCommonUtils.getUserCode());
        mjOrder.setUpdateId(MoJiCommonUtils.getUserCode());
        mjOrder.setCreateTime(new Date());
        mjOrder.setUpdateTime(new Date());

        if (ObjectUtil.isEmpty(addOrderDto.getOrderDetailList())) {
            throw new RuntimeException("订单明细不存在,请核查!");
        }
        StringBuffer orderName = new StringBuffer();
        StringBuffer productType = new StringBuffer();
        addOrderDto.getOrderDetailList().forEach(item -> {
            String detailCode = idGenerator.idGenerator("DDMX");
            item.setOrderCode(orderCode);
            item.setOrderMxCode(detailCode);
            //产品类型  1 免费版  2 包年版  3 个性定制版
            if ("1".equals(item.getServiceType())) {
                //校验是否重复申请
                LambdaQueryWrapper<MjOrderDetail> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(MjOrderDetail::getServiceCityCode, item.getServiceCityCode());
                wrapper.eq(MjOrderDetail::getCallWayCode, item.getCallWayCode());
                wrapper.eq(MjOrderDetail::getCallCountCode, item.getCallCountCode());
                wrapper.eq(MjOrderDetail::getServiceTimeCode, item.getServiceTimeCode());
                wrapper.eq(MjOrderDetail::getServiceType, item.getServiceType());
                wrapper.eq(MjOrderDetail::getCreateId, MoJiCommonUtils.getUserCode());
                wrapper.eq(ObjectUtil.isNotEmpty(item.getWeatherTypeCode()), MjOrderDetail::getWeatherTypeCode, item.getWeatherTypeCode());
                wrapper.eq(ObjectUtil.isNotEmpty(item.getGlobalCityCode()), MjOrderDetail::getGlobalCityCode, item.getGlobalCityCode());
                MjOrderDetail mjOrderDetail = mjOrderDetailService.getOne(wrapper);
                if (mjOrderDetail != null) {
                    throw new RuntimeException("该免费申请测试已经申请过,不能二次申请,请核查!");
                }
                item.setOrderName("免费版");
                mjOrder.setPayType("3");
            }
            if ("2".equals(item.getServiceType())) {
                item.setOrderName("包年版");
            }
            if ("3".equals(item.getServiceType())) {
                item.setOrderName("个性定制版");
            }
            orderName.append(item.getOrderName() + "/");
            productType.append(item.getServiceType() + ",");

            item.setUseStatus(0);
            item.setCreateId(MoJiCommonUtils.getUserCode());
            item.setUpdateId(MoJiCommonUtils.getUserCode());
            item.setCreateTime(new Date());
            item.setUpdateTime(new Date());
            mjOrderDetailService.save(item);
        });
        if (ObjectUtil.isNotEmpty(orderName)) {
            mjOrder.setOrderName(orderName.substring(0, orderName.length() - 1));
        }
        if (ObjectUtil.isNotEmpty(productType)) {
            mjOrder.setProductType(productType.substring(0, productType.length() - 1));
        }
        if (this.save(mjOrder)) {
            return mjOrder;
        }
        return null;
    }

    @Override
    public boolean edit(AddOrderDto addOrderDto) {
        MjOrder mjOrder = this.getById(addOrderDto.getId());
        BeanUtils.copyProperties(addOrderDto, mjOrder);
        mjOrder.setUpdateId(MoJiCommonUtils.getUserCode());
        mjOrder.setUpdateTime(new Date());
        if (ObjectUtil.isEmpty(addOrderDto.getOrderDetailList())) {
            throw new RuntimeException("订单明细不存在,请核查!");
        }
        //删除旧的明细
        LambdaQueryWrapper<MjOrderDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MjOrderDetail::getOrderCode, addOrderDto.getOrderCode());
        mjOrderDetailService.remove(wrapper);
        addOrderDto.getOrderDetailList().forEach(item -> {
            String detailCode = idGenerator.idGenerator("DDMX");
            item.setOrderCode(addOrderDto.getOrderCode());
            item.setOrderMxCode(detailCode);
            item.setCreateId(MoJiCommonUtils.getUserCode());
            item.setUpdateId(MoJiCommonUtils.getUserCode());
            item.setCreateTime(new Date());
            item.setUpdateTime(new Date());
            mjOrderDetailService.save(item);
        });
        return this.updateById(addOrderDto);
    }

    @Override
    public OrderVo detail(Long id) {
        OrderVo orderVo = new OrderVo();
        MjOrder mjOrder = this.getById(id);
        if (mjOrder == null) {
            throw new RuntimeException("订单数据不存在,请核查!");
        }
        if (mjOrder.getSpareInt1() != null) {
            if (mjOrder.getSpareInt1() == 3) {
                mjOrder.setRefuse(false);
            } else {
                mjOrder.setRefuse(true);
            }
        } else {
            if(mjOrder.getPayTime()==null)
            {
                mjOrder.setRefuse(false);
            }else{
                mjOrder.setRefuse(true);
            }
        }
        BeanUtils.copyProperties(mjOrder, orderVo);
        LambdaQueryWrapper<MjOrderDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MjOrderDetail::getOrderCode, mjOrder.getOrderCode());
        List<MjOrderDetail> detailList = mjOrderDetailService.list(wrapper);
        for (int i = 0; i < detailList.size(); i++) {
            if (detailList.get(i) != null) {
                if ("N1Y".equals(detailList.get(i).getServiceTimeCode())) {
                    if (detailList.get(i).getEffectTime() != null) {
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(detailList.get(i).getEffectTime());
                        calendar.add(Calendar.YEAR, 1);
                        detailList.get(i).setExpirationTime(calendar.getTime());
                    }

                } else if ("N2Y".equals(detailList.get(i).getServiceTimeCode())) {
                    {
                        if (detailList.get(i).getEffectTime() != null) {
                            Calendar calendar = Calendar.getInstance();
                            calendar.setTime(detailList.get(i).getEffectTime());
                            calendar.add(Calendar.YEAR, 2);
                            detailList.get(i).setExpirationTime(calendar.getTime());
                        }
                    }
                } else if ("T7D".equals(detailList.get(i).getServiceTimeCode())) {
                    if (detailList.get(i).getEffectTime() != null) {
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(detailList.get(i).getEffectTime());
                        calendar.add(Calendar.DAY_OF_MONTH, 7);
                        detailList.get(i).setExpirationTime(calendar.getTime());
                    }
                }

            }

        }
        orderVo.setOrderDetailList(detailList);
        return orderVo;
    }

    @Override
    public InputStream getFileInputStream() throws IOException {
        LambdaQueryWrapper<MjAgreement> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MjAgreement::getType, 4);
        MjAgreement mjAgreement = mjAgreementService.getOne(wrapper);
        if (mjAgreement != null) {
            String filePath = mjAgreement.getUrl();
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build("https://oss-cn-beijing.aliyuncs.com", "LTAI5tKfuAtpE8aykxckGeHu", "q8cCZFNBTZsYCGNmUbO4fg2ABBOVLT");
            //获取文件io流
            //截取地址
            int index = filePath.indexOf("aliyuncs.com");
            filePath = filePath.substring(index + "aliyuncs.com".length() + 1);
            OSSObject ossObject = ossClient.getObject("testmoji", filePath);
            try {
                InputStream out = ossObject.getObjectContent();
                byte[] bytes = toByteArray(out);
                return new ByteArrayInputStream(bytes);
            } finally {
                ossClient.shutdown();
            }
        } else {
            return null;
        }
    }

    @Override
    public StatisticsVo statistics(QueryOrderDto dto) {
        StatisticsVo statisticsVo = new StatisticsVo();
        LambdaQueryWrapper<MjOrderDetail> wrapper = new LambdaQueryWrapper<>();
        //wrapper.eq(MjOrderDetail::getUseStatus, 1);
        wrapper.eq(ObjectUtil.isNotEmpty(dto.getProductType()), MjOrderDetail::getServiceType, dto.getProductType());
        wrapper.eq(MjOrderDetail::getCreateId, MoJiCommonUtils.getUserCode());
        List<MjOrderDetail> detailList = mjOrderDetailService.list(wrapper);
        StringBuffer expirationTimeStr = new StringBuffer();
        StringBuffer mxCode = new StringBuffer();
        StringBuffer secretKey = new StringBuffer();
        StringBuffer weatherTypeCode = new StringBuffer();
        StringBuffer weatherType = new StringBuffer();
        if (ObjectUtil.isNotEmpty(detailList)) {
            for (MjOrderDetail mjOrderDetail : detailList) {
                //订单明细
                mxCode.append(mjOrderDetail.getOrderMxCode() + ",");
                //密钥
                if (ObjectUtil.isNotEmpty(mjOrderDetail.getSpareString2())) {
                    secretKey.append(mjOrderDetail.getSpareString2() + ",");
                }
                //天气类型
                if (ObjectUtil.isNotEmpty(mjOrderDetail.getWeatherType())) {
                    if(mjOrderDetail.getWeatherType().contains("/")){
                        weatherType.append(mjOrderDetail.getWeatherType().substring(0, mjOrderDetail.getWeatherType().indexOf("/")) + ",");
                    }else{
                        weatherType.append(mjOrderDetail.getWeatherType()+ ",");

                    }
                }
                //天气类型编码
                if (ObjectUtil.isNotEmpty(mjOrderDetail.getWeatherTypeCode())) {
                    if(mjOrderDetail.getWeatherTypeCode().contains("/")){
                        weatherTypeCode.append(mjOrderDetail.getWeatherTypeCode().substring(0, mjOrderDetail.getWeatherTypeCode().indexOf("/")) + ",");
                    }else{
                        weatherTypeCode.append(mjOrderDetail.getWeatherTypeCode()+ ",");

                    }
                }
                //天气类型
                if (ObjectUtil.isNotEmpty(mjOrderDetail.getGlobalCity())) {
                    if(mjOrderDetail.getGlobalCity().contains("/")){
                        weatherType.append(mjOrderDetail.getGlobalCity().substring(0, mjOrderDetail.getGlobalCity().indexOf("/")) + ",");
                    }else{
                        weatherType.append(mjOrderDetail.getGlobalCity()+ ",");

                    }
                }
                //天气类型编码
                if (ObjectUtil.isNotEmpty(mjOrderDetail.getGlobalCityCode())) {
                    if(mjOrderDetail.getGlobalCityCode().contains("/")){
                        weatherTypeCode.append(mjOrderDetail.getGlobalCityCode().substring(0, mjOrderDetail.getGlobalCityCode().indexOf("/")) + ",");
                    }else{
                        weatherTypeCode.append(mjOrderDetail.getGlobalCityCode()+ ",");

                    }
                }
                //服务到期时间
                if (ObjectUtil.isNotEmpty(mjOrderDetail.getServiceTimeCode())) {
                    if ("N1Y".equals(mjOrderDetail.getServiceTimeCode())) {
                        if (mjOrderDetail.getEffectTime() != null) {
                            Calendar calendar = Calendar.getInstance();
                            calendar.setTime(mjOrderDetail.getEffectTime());
                            calendar.add(Calendar.YEAR, 1);
                            mjOrderDetail.setExpirationTime(calendar.getTime());
                            expirationTimeStr.append(DateUtils.formatDate(mjOrderDetail.getExpirationTime(), DateUtils.DATETIME_FORMAT) + ",");
                        }
                    } else if ("N2Y".equals(mjOrderDetail.getServiceTimeCode())) {
                        {
                            if (mjOrderDetail.getEffectTime() != null) {
                                Calendar calendar = Calendar.getInstance();
                                calendar.setTime(mjOrderDetail.getEffectTime());
                                calendar.add(Calendar.YEAR, 2);
                                mjOrderDetail.setExpirationTime(calendar.getTime());
                                expirationTimeStr.append(DateUtils.formatDate(mjOrderDetail.getExpirationTime(), DateUtils.DATETIME_FORMAT) + ",");
                            }
                        }

                    } else if ("T7D".equals(mjOrderDetail.getServiceTimeCode())) {
                        if (mjOrderDetail.getEffectTime() != null) {
                            Calendar calendar = Calendar.getInstance();
                            calendar.setTime(mjOrderDetail.getEffectTime());
                            calendar.add(Calendar.DAY_OF_MONTH, 7);
                            mjOrderDetail.setExpirationTime(calendar.getTime());
                            expirationTimeStr.append(DateUtils.formatDate(mjOrderDetail.getExpirationTime(), DateUtils.DATETIME_FORMAT) + ",");
                        }

                    }
                }
            }
            statisticsVo.setOrderCode(detailList.get(0).getOrderCode());
            if (ObjectUtil.isNotEmpty(mxCode)) {
                statisticsVo.setOrderMxCode(mxCode.toString().substring(0, mxCode.length() - 1));
            }
            statisticsVo.setCount(detailList.size());
            statisticsVo.setServiceType(dto.getProductType());
            statisticsVo.setOrderName("1".equals(dto.getProductType()) ? "免费版" : "包年版");
            statisticsVo.setUseStatus(detailList.get(0).getUseStatus());
            if (ObjectUtil.isNotEmpty(expirationTimeStr)) {
                statisticsVo.setExpirationTime(expirationTimeStr.toString().substring(0, expirationTimeStr.toString().length() - 1));
            }
            //天气类型
            if (ObjectUtil.isNotEmpty(weatherType)) {
                statisticsVo.setWeatherType(weatherType.toString().substring(0, weatherType.length() - 1));
            }
            //天气类型编码
            if (ObjectUtil.isNotEmpty(weatherTypeCode)) {
                statisticsVo.setWeatherTypeCode(weatherTypeCode.toString().substring(0, weatherTypeCode.length() - 1));
            }
            if (ObjectUtil.isNotEmpty(secretKey)) {
                statisticsVo.setSecretKey(secretKey.toString().substring(0, secretKey.length() - 1));
            } else {
                statisticsVo.setSecretKey("");
            }
        }
        return statisticsVo;
    }

    @Override
    public MijiMoYaoVo2.DataBean brief(String tokens) {
        String s = HttpUtils.doGet2("http://demo.mojicb.com/eshop-statistic/v1/mds-brief?tokens=" + tokens);
        Gson gson1 = new Gson();
        MijiMoYaoVo1 mijiMoYaoVo1 = gson1.fromJson(s, MijiMoYaoVo1.class);
        if (mijiMoYaoVo1 != null && mijiMoYaoVo1.getCode() == 200) {
            Gson gson2 = new Gson();
            MijiMoYaoVo2 mijiMoYaoVo2 = gson2.fromJson(s, MijiMoYaoVo2.class);
            MijiMoYaoVo2.DataBean data = mijiMoYaoVo2.getData();
            return data;
        }
        return null;
    }

    @Override
    public MijiMoYao3.DataBean tsData(String tokens, String aggType, String startTime, String endTime) {
        String url = "http://demo.mojicb.com/eshop-statistic/v1/mds-tsdata?tokens=" + tokens + "&aggType=" + aggType
                + "&startTime=" + startTime + "&endTime=" + endTime;
        String replace = url.replace(" ", "%20");
        String s = HttpUtils.doGet3(replace);
        Gson gson1 = new Gson();
        MijiMoYaoVo1 mijiMoYaoVo1 = gson1.fromJson(s, MijiMoYaoVo1.class);
        if (mijiMoYaoVo1 != null && mijiMoYaoVo1.getCode() == 200) {
            Gson gson2 = new Gson();
            MijiMoYao3 mijiMoYaoVo2 = gson2.fromJson(s, MijiMoYao3.class);
            MijiMoYao3.DataBean data = mijiMoYaoVo2.getData();
            return data;
        }
        return null;
    }

    /**
     * InputStream流转byte数组
     *
     * @param input
     * @return
     * @throws IOException
     */
    public static byte[] toByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[input.available()];
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return output.toByteArray();
    }
}
